import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'core/database_helper.dart';
import 'core/app_config.dart';
import 'state/auth_provider.dart';
import 'views/screens/login_screen.dart';
import 'views/screens/user_management_screen.dart';
import 'views/screens/carbon_footprint_list_screen.dart';
import 'views/screens/statistics_screen.dart';
import 'views/screens/system_settings_screen.dart';

void main() async {
  // 确保Flutter绑定初始化
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化数据库
  await DatabaseHelper.initializeDatabaseFactory();
  final dbHelper = DatabaseHelper();
  
  // 开发模式下强制重新创建数据库（确保使用最新的密码哈希值）
  const bool isDevelopment = false; // 开发模式标志
  if (isDevelopment) {
    await dbHelper.forceRecreateDatabase();
  } else {
    await dbHelper.database;
  }
  
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => AuthProvider()),
      ],
      child: MaterialApp(
        title: AppConfig.appName,
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primarySwatch: Colors.blue,
          primaryColor: Color(AppConfig.primaryColor),
          colorScheme: ColorScheme.fromSeed(
            seedColor: Color(AppConfig.primaryColor),
            brightness: Brightness.light,
          ),
          useMaterial3: true,
          // 自定义主题
          appBarTheme: const AppBarTheme(
            backgroundColor: Color(0xFF1976D2),
            foregroundColor: Colors.white,
            elevation: 0,
            centerTitle: true,
          ),
          elevatedButtonTheme: ElevatedButtonThemeData(
            style: ElevatedButton.styleFrom(
              backgroundColor: Color(AppConfig.primaryColor),
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(AppConfig.defaultRadius),
              ),
              elevation: AppConfig.defaultElevation,
            ),
          ),
          inputDecorationTheme: InputDecorationTheme(
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppConfig.defaultRadius),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppConfig.defaultRadius),
              borderSide: const BorderSide(color: Color(0xFF1976D2), width: 2),
            ),
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 12,
            ),
          ),
          cardTheme: CardTheme(
            elevation: AppConfig.defaultElevation,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(AppConfig.defaultRadius),
            ),
          ),
        ),
        home: const LoginScreen(),
        routes: {
          '/login': (context) => const LoginScreen(),
          '/home': (context) => const HomeScreen(),
          '/user-management': (context) => const UserManagementScreen(),
          '/carbon-footprint': (context) => const CarbonFootprintListScreen(),
          '/statistics': (context) => const StatisticsScreen(),
          '/system-settings': (context) => const SystemSettingsScreen(),
        },
      ),
    );
  }
}

/// 主界面
class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(AppConfig.appName),
        actions: [
          IconButton(
            icon: const Icon(Icons.logout),
            onPressed: () => _handleLogout(context),
          ),
        ],
      ),
      body: Consumer<AuthProvider>(
        builder: (context, authProvider, child) {
          if (!authProvider.isLoggedIn) {
            return const Center(
              child: Text('请先登录'),
            );
          }

          return Padding(
            padding: const EdgeInsets.all(AppConfig.defaultPadding),
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 欢迎信息
                  _buildWelcomeSection(authProvider),
                  const SizedBox(height: 24),
                  
                  // 功能模块
                  _buildFeatureModules(context, authProvider),
                  const SizedBox(height: 24),
                  
                  // 统计信息
                  _buildStatisticsSection(),
                  const SizedBox(height: 24), // 添加底部间距
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  /// 构建欢迎区域
  Widget _buildWelcomeSection(AuthProvider authProvider) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                CircleAvatar(
                  backgroundColor: Color(AppConfig.primaryColor),
                  child: Text(
                    authProvider.currentUser?.displayName.substring(0, 1).toUpperCase() ?? 'U',
                    style: const TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '欢迎回来，${authProvider.currentUser?.displayName ?? '用户'}',
                        style: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Text(
                        authProvider.currentUser?.roleName ?? '用户',
                        style: const TextStyle(
                          color: Color(0xFF757575),
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建功能模块
  Widget _buildFeatureModules(BuildContext context, AuthProvider authProvider) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '功能模块',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 16),
        
        GridView.count(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          crossAxisCount: 2,
          crossAxisSpacing: 16,
          mainAxisSpacing: 16,
          childAspectRatio: 1.2,
          children: [
            // 碳足迹记录
            _buildFeatureCard(
              context,
              '碳足迹记录',
              Icons.eco,
              Color(AppConfig.accentColor),
              () => _navigateToFeature(context, 'carbon_footprint'),
            ),
            
            // 统计分析
            _buildFeatureCard(
              context,
              '统计分析',
              Icons.analytics,
              Color(AppConfig.primaryColor),
              () => _navigateToFeature(context, 'statistics'),
            ),
            
            // 用户管理（仅管理员可见）
            if (authProvider.isAdmin)
              _buildFeatureCard(
                context,
                '用户管理',
                Icons.people,
                Color(AppConfig.warningColor),
                () => _navigateToFeature(context, 'user_management'),
              ),
            
            // 系统设置
            _buildFeatureCard(
              context,
              '系统设置',
              Icons.settings,
              Color(0xFF757575),
              () => _navigateToFeature(context, 'settings'),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建功能卡片
  Widget _buildFeatureCard(
    BuildContext context,
    String title,
    IconData icon,
    Color color,
    VoidCallback onTap,
  ) {
    return Card(
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(AppConfig.defaultRadius),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                icon,
                size: 48,
                color: color,
              ),
              const SizedBox(height: 12),
              Text(
                title,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建统计信息区域
  Widget _buildStatisticsSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '系统统计',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 16),
        
        Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                _buildStatItem('总记录数', '0', Icons.list),
                const Divider(),
                _buildStatItem('本月新增', '0', Icons.add),
                const Divider(),
                _buildStatItem('总碳排放', '0 吨', Icons.cloud),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建统计项
  Widget _buildStatItem(String label, String value, IconData icon) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        children: [
          Icon(
            icon,
            color: Color(AppConfig.primaryColor),
            size: 20,
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              label,
              style: const TextStyle(
                color: Color(0xFF757575),
              ),
            ),
          ),
          Text(
            value,
            style: const TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 16,
            ),
          ),
        ],
      ),
    );
  }

  /// 导航到功能页面
  void _navigateToFeature(BuildContext context, String feature) {
    switch (feature) {
      case 'user_management':
        Navigator.of(context).pushNamed('/user-management');
        break;
      case 'carbon_footprint':
        Navigator.of(context).pushNamed('/carbon-footprint');
        break;
      case 'statistics':
        Navigator.of(context).pushNamed('/statistics');
        break;
      case 'settings':
        Navigator.of(context).pushNamed('/system-settings');
        break;
      default:
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('$feature 功能开发中...'),
            backgroundColor: Color(AppConfig.warningColor),
          ),
        );
    }
  }

  /// 处理登出
  void _handleLogout(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('确认登出'),
          content: const Text('确定要退出登录吗？'),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop();
                Provider.of<AuthProvider>(context, listen: false).logout();
                Navigator.of(context).pushReplacementNamed('/login');
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }
}
